import {useCommonInfoStore} from "../../stores/modules/commonInfo";
import {useUserInfoStore} from "../../stores/modules/userInfo";
import {ref} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import {accountCancelAPI, setMeiTuanTel, updateConfigAPI} from "../../services/me";
import {conUtils} from "../../utils/conUtils";
import {codeBindAPI} from "../../services/makeMoney";
import checkVersion from "../lq-upgrade/checkVersion";
import {useOrderInfoStore} from "../../stores/modules/orderInfo";

export const useSetting = () => {
    // 公共信息
    const useCommonInfo = useCommonInfoStore()
    // 用户信息
    const userInfoStore = useUserInfoStore()
    // 本地订单刷新处理
    const orderInfoStore = useOrderInfoStore()
    // 最新用户信息
    const user = ref()
    // 修改昵称弹框是否显示
    const show = ref(false)
    // 退出登录加载框是否显示
    const Loingshow = ref(false)
    // 注销弹框提示是否显示
    const zhuxiaoshow = ref(false)
    // 美团手机号
    const mttel = ref()
    // 上级ID
    const parent_id = ref(0)

    // 系统版本号
    const version = ref()
    // 是否检查更新
    const checked = ref(false)
    // 修改手机号弹框
    const phonePop = ref(false)
    // 是否可以绑定上级团长
    const inPutTemCode = ref(false)
    // 用户手机号
    const tel = ref("")
    // 验证码
    const temCode = ref("")
    // 更新数据
    const updateData = ref()
    // 当前系统来自那个平台
    const platform = uni.getSystemInfoSync().platform;


    onLoad(async () => {
        // 是否检查版本更新
        checked.value = userInfoStore.tuiSong || false
        // #ifdef APP-PLUS
        // APP获取版本号并检查更新
        plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
            version.value = wgtinfo.version //应用版本号
        })
        await checkUpdate()
        // #endif
    })


    // 退出登录
    const exitConfirm = async () => {
        // 清空订单页面
        orderInfoStore.isRefresh = true
        Loingshow.value = false
        // 清楚用户数据
        await userInfoStore.clearProfile()
        useCommonInfo.clearId()
        uni.reLaunch( {
            url: '/pages/me/me'
        })
    }
    // 注销账号
    const outCountConfirm = async () => {
        zhuxiaoshow.value = false
        const res = await accountCancelAPI({})
        if (res.status === 1) {
            await uni.showToast({
                title: res.msg,
                icon: 'none'
            })
            setTimeout(function () {
                orderInfoStore.isRefresh = true
                useCommonInfo.clearId()
                userInfoStore.clearProfile()
            }, 2000);
        } else {
            await uni.showToast({
                title: res.msg,
                icon: 'none'
            })
        }
    }

    // 修改手机号 type = 1 修改密码 type = 3 修改手机号
    const handleChangeLoginPassword = (type) => {
        uni.navigateTo({
            url: '/pages/login/updatephoneandpass?is_change=' + type
        })
    }
    // 绑定手机号
    const submitTel = async () => {
        if (!/^1[0-9]{10}$/.test(tel.value)) { // 使用正则表达式进行校验
            await uni.showToast({title: "手机号错误，请重新输入", icon: "none"})
        } else {
            console.log("是有效的手机号");
            await setMeiTuanTel(tel.value)
            await userInfoStore.getUserInfo()
            await uni.showToast({title: "绑定成功", icon: "none"})
            await close()
        }
    }
    // 绑定上级团长
    const submitTemCode = async () => {
        if (temCode.value.length === 0) {
            await uni.showToast(
                {title: "请输入邀请码", icon: "none"})
            return
        }
        // uni.showToast({title:temCode.value.indexOf('[') + ""})
        if (temCode.value.length > 8 && temCode.value.indexOf('[') !== -1 && temCode.value.indexOf(']') !== -1) {
            temCode.value = temCode.value.split('[')[1]
            temCode.value = temCode.value.split(']')[0]
        }
        await codeBindAPI(temCode.value)
        await uni.showToast({title: "绑定成功", icon: "none"})
        await close()
    }
    // 修改美团手机号
    const changeMTTel = () => {
        phonePop.value = true
        conUtils("changeMTTel", mttel.value)
    }
    // 手动关闭美团膝盖手机号时初始化默认值
    const close = async () => {
        await userInfoStore.getUserInfo()
        phonePop.value = false
        inPutTemCode.value = false
        user.value = userInfoStore.userInfo
        tel.value = user.value?.mt_phone
        parent_id.value = user.value?.parent_id
    }
    // 修改是否开启个性化推送
    const changeis = (e) => {
        console.log(e)
        userInfoStore.setTuiSong(e);
    }

    // 检查更新
    const checkUpdate = async () => {
        // #ifdef APP-PLUS
        const {result} = await updateConfigAPI()
        if (platform === 'ios') {
            updateData.value = result.ios_version_config
        } else {
            updateData.value = result.android_version_config
        }
        let name = updateData.value.version;  //新版本名称
        let code = updateData.value.code; //新版本号（数字）
        let content = updateData.value.content;  //更新内容
        let app_url = updateData.value.url;  //wgt下载链接，（演示请换成真正在下载链接）
        let wgt_url = updateData.value.wgt_url;  //app下载链接，（演示请换成真正在下载链接）
        let forceUpdate = updateData.value.forceUpdate !== 0;//是否强制更新
        let hot_version = updateData.value.hot_version;//允许热更新的范围
        //检查是否需要更新
        checkVersion({
            name,//最新版本名称
            code,//最新版本号
            content,//更新内容
            app_url,//下载链接
            wgt_url,//下载链接
            forceUpdate,//是否强制升级
            hot_version,//是否整包更新
        })
        // #endif
    }
    return {
        useCommonInfo,
        userInfoStore,
        user,
        show,
        Loingshow,
        orderInfoStore,
        zhuxiaoshow,
        mttel,
        parent_id,
        version,
        phonePop,
        inPutTemCode,
        tel,
        temCode,
        checked,
        updateData,
        platform,
        close,
        changeis,
        checkUpdate,
        submitTel,
        changeMTTel,
        submitTemCode,
        exitConfirm,
        outCountConfirm,
        handleChangeLoginPassword,
    }
}